package com.hfstu.framework.webmsg;


import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.proxy.ScriptProxy;

import com.hfstu.framework.common.ApplicationSessionSchema;
import com.hfstu.framework.core.utils.web.dwr.DwrUtil;
import com.hfstu.framework.util.StringUtil;



public class WebMessageUtil {
	private static final String PAGE_NAME = "/index.html";
	private static final String POPWEBMESSAGE_METHODNAME = "popWebSystemMessage";

	protected static boolean validScriptSession(
			Collection<ScriptSession> sessions) {
		for (Iterator<ScriptSession> it = sessions.iterator(); it.hasNext();) {
			ScriptSession session = it.next();
			if (!session.isInvalidated()) {
				long time = new Date().getTime()
						- session.getLastAccessedTime();
				if (time < 200000)// 最近一次连接时间为3分钟内
					return true;
			}
		}
		return false;
	}

	/**
	 * 得到接收者的ScriptSession
	 * 
	 * @param userid
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected static Collection<ScriptSession> getScriptSession(String userId,
			HttpServletRequest request) {
		Collection<ScriptSession> scriptSessions = new HashSet<ScriptSession>();
		Map<String, Map<String, ScriptSession>> map = (Map<String, Map<String, ScriptSession>>) request
				.getSession().getServletContext()
				.getAttribute(ApplicationSessionSchema.DWR_ONLINE_INFO);
		if (map != null) {
			Map<String, ScriptSession> ss = map.get(userId);
			if (ss != null){
				scriptSessions.addAll(ss.values());
			}
			
		}
		return scriptSessions;
	}

	/**
	 * 发送消息给指定的人员
	 * 
	 * @param sender
	 *            发送者
	 * @param receiverid
	 *            接收者
	 * @param msg
	 *            消息内容
	 * @return true:用户在线消息发送,false:用户不在线消息废弃,您可以做相应的处理如保存此消息到数据库
	 */
	public static boolean sendMsgToOne(String sender, String receiverid,
			String msg, HttpServletRequest request) {
		Collection<ScriptSession> session = getScriptSession(receiverid,
				request);
		if (!(session == null || session.size() == 0)) {
			ScriptProxy sp = new ScriptProxy(session);
			sp.addFunctionCall(POPWEBMESSAGE_METHODNAME, msg);
			System.out.println("------用户在线发送系统消息---------");
			return true;
		} else {
			System.out.println("------用户不在线，消息废除---------");
			return false;
		}

	}

	/**
	 * 发送消息给指定的人员
	 * 
	 * @param sender
	 *            发送者
	 * @param receiverId
	 *            如:xxx,xxx 接收者
	 * @param msg
	 *            消息内容
	 */
	public static void sendMsgToMany(String sender, String receiverId,
			String msg, HttpServletRequest request) {
		String[] userIds = receiverId.split(",");
		Collection<ScriptSession> sessions = new HashSet<ScriptSession>();
		for (String userId : userIds) {
			if (!StringUtil.isNullOrEmpty(userId)) {
				Collection<ScriptSession> session = getScriptSession(userId,
						request);
				if (session != null) {
					sessions.addAll(session);
				}

			}
		}
		ScriptProxy sp = new ScriptProxy(sessions);
		sp.addFunctionCall(POPWEBMESSAGE_METHODNAME, msg);

	}

	/**
	 * 发送web消息给所有的在线用户
	 * 
	 * @param msg
	 */
	@SuppressWarnings("unchecked")
	public static void sendMsgToAll(String msg) {
		HttpServletRequest request = DwrUtil.getRequest();
		Collection<ScriptSession> sessions = new HashSet<ScriptSession>();
		sessions.addAll(ServerContextFactory.get(
				request.getSession().getServletContext())
				.getScriptSessionsByPage(PAGE_NAME));
		ScriptProxy sp = new ScriptProxy(sessions);
		sp.addFunctionCall(POPWEBMESSAGE_METHODNAME, msg);
	}

}
